package com.chatdating.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class CosService {

    // 腾讯云配置
    private static final String secretId = "AKID02UBqOJLLKJPTQGvbAf1EHF5kJCCQm5L";
    private static final String secretKey = "EJY2VvLhEf3NoZZ4jHykP3fFoVFvYJ0a";
    private static final String bucketName = "chatdating1-1328529875";   // 存储桶名称
    private static final String region = "ap-guangzhou";            // 存储桶地域
    // 获取COS客户端
    private COSClient getCosClient() {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        return new COSClient(cred, clientConfig);
    }

    // 上传文件到COS
    public String uploadFile(MultipartFile file, String fileType) {
        if (file.isEmpty()) {
            return null;
        }

        COSClient cosClient = getCosClient();
        try {
            // 生成文件名 (用户ID+时间戳+类型)
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));   //扩展名
            String key = fileType + "/" +UUID.randomUUID() + fileExt;

            // 创建上传请求
            File tempFile = File.createTempFile("upload", fileExt);
            file.transferTo(tempFile);
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, tempFile);

            // 执行上传
            cosClient.putObject(putObjectRequest);

            // 返回文件URL (根据你的配置可能需要拼接)
            return "https://" + bucketName + ".cos." + region + ".myqcloud.com/" + key;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            cosClient.shutdown();
        }
    }
}
